// roleManage.js
import {Button, Form, Input, Popconfirm, Table, Select, message,Modal} from 'antd';
import {useNavigate} from 'react-router-dom';
import React, { useState,useEffect } from 'react';
import './index.scss';
import {observer} from 'mobx-react';
import store from '../../../store';

const { Option } = Select;
const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === 'number' ? (<Select disabled>
        <Option value="正常">正常</Option>
        <Option value="冻结">冻结</Option>
    </Select>) : <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            rules={[
              {
                required: true,
                message: `请填写 ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
};
const RoleManage = ()=>{
  const {Role} = store;
  const navigate = useNavigate();
  // 初始化函数
  const initFn = ()=>{
    Role.getRoles();
  }
  useEffect(()=>{      
    if(Role.roleData.length===0){
      initFn(); 
    }
  },[])
  
    // 创建角色    
    const createRole = ()=>{  
      let maxId = Role.roleData.map(item=>item.id);
      maxId = Math.max(...maxId);
      const newData = {
          roleName: 'ceshi'+(maxId+1),//是英文名字用来控制权限的
          roleRemark: '请输入角色名称'//中文名列入'超级管理员'
      };
      Role.addRole(newData).then(data=>{
        if(data.code===200){
          initFn();
        }else{
          message.error('添加失败');
        }
      })    
    }
    const power = ()=>{
        navigate('/home/power');
    }
    // 表格
    const [form] = Form.useForm();
    
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record) => record.id === editingKey;
    // 编辑
    const edit = (record) => {
      form.setFieldsValue({
          id: '',
          roleMark: '',
          roleTime: '',
          roleStatus: '',
          ...record,
      });
      setEditingKey(record.id);
    };
    // 取消编辑
    const cancel = ()=>{
        setEditingKey('');
    };
    // 保存
    const save = async (id) => {
        try {
          const row = await form.validateFields();
          const newData = [...Role.roleData];
          const index = newData.findIndex((item) => id === item.id);
    
          if (index > -1) {
            const item = newData[index];
            newData.splice(index, 1, { ...item, ...row });
            Role.changeRole(newData[index]).then(data=>{
              if(data.code===200){
                message.success('修改成功');
                initFn();
              }else{
                message.error('修改失败');
              }
            })
            console.log(newData[index]);
            setEditingKey('');
          } else {
            newData.push(row);
            // setData(newData);
            Role.addRole(row);
            setEditingKey('');
          }
        } catch (errInfo) {
          console.log('Validate Failed:', errInfo);
        }
    };
    // 冻结 解冻
    const freeze =(record)=>{
      console.log(record);
      if(record.roleStatus==='正常'){
        Role.freezeRole(record.id).then(data=>{
          if(data.code===200){
            message.success('冻结成功');
            initFn();
          }else{
            message.error('冻结失败')
          }
        })
      }else{
        Role.unfreeRole(record.id).then(data=>{
          if(data.code===200){
            message.success('解冻成功');
            initFn();
          }else{
            message.error('解冻失败')
          }
        })
      }
      
    };
    // 删除
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [itemData,setItem] = useState('');
    const del = (record)=>{
      setIsModalOpen(true)
      setItem(record)
    };
    const handleOk = ()=>{
      Role.delRole(itemData.id).then(data=>{
        if(data.code===200){
          setIsModalOpen(false);
          message.success('删除成功');
          initFn();
        }else{
          message.error('删除失败')
        }
      })
      initFn();
    };
    const handleCancel = ()=>{
      setIsModalOpen(false);
      message.warning('已取消删除')
    }
    // 表头
    const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      width: '10%',
      editable: false,
    },
    {
      title: '角色名',
      dataIndex: 'roleMark',
      width: '15%',
      editable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'roleTime',
      width: '20%',
      editable: false,
    },
    {
        title: '状态',
        dataIndex: 'roleStatus',
        width: '20%',
        editable: true,
      },
    {
      title: '操作',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Button onClick={() => save(record.id)} type="link" >
              保存
            </Button>
            <Popconfirm title="确定取消编辑?" onConfirm={cancel} okText="是" cancelText="否">
              <span style={{cursor: 'pointer'}}>取消</span>
            </Popconfirm>
          </span>
        ) : (
          <>
            <Button type='link' disabled={editingKey !== ''} onClick={() => edit(record)}>
             编辑
            </Button>
            <Button type='link' disabled={editingKey !== ''} onClick={() => freeze(record)}>
            {record.roleStatus==='正常'?'冻结':'激活'}
            </Button>
            <Button type='link' disabled={editingKey !== ''} onClick={() => del(record)}>
              删除
            </Button>
          </>
          
        );
      },
    },
    ];
    const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'roleStatus' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
    });

    return <>
        <div className='role_top'>角色管理</div>
        {/* 上 */}
        <Button className='btn' onClick={createRole}>创建角色</Button>
        <Button className='btn' onClick={power}>权限配置</Button>
        {/* 中 */}
        <Form form={form} component={false}>
            <Table
                components={{
                body: {
                    cell: EditableCell,
                },
                }}
                bordered
                dataSource={Role.roleData}
                columns={mergedColumns}
                rowClassName="editable-row"
                pagination={{
                onChange: cancel,
                pageSize: 5
                }}
                rowKey={(record=>record.id)}
            />
        </Form>
        {/* 确认删除 */}
        <Modal title="冻结" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
        okText="确认" cancelText="取消">
            <p>您确定要删除选择的{itemData.roleMark}这个角色吗？</p>
        </Modal>
    </>
}
export default observer(RoleManage)